import React, { useRef, useState } from 'react';
import { connect, Dispatch } from 'umi';

import { Divider, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import { ActionType, ProColumns } from '@ant-design/pro-table/lib/Table';
import { SorterResult } from 'antd/es/table/interface';

const AddModel = React.lazy(() => import('./components/AddModel'));
const RightsManagement = React.lazy(() => import('../components/RightsManagement'));
const RelationModel = React.lazy(() => import('../components/RelationModel'));

import { IOrganizeTableItem } from '@/pages/data.d';
import { ConnectState } from '@/models/connect';
import { UserTableListItem } from '../type';

interface TemporaryAuthorityProps {
  dispatch: Dispatch;
}

const TemporaryAuthority: React.FC<TemporaryAuthorityProps> = (props) => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 新建弹框
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false); // 权限管理弹框
  const [distributionObj, setDistributionObj] = useState<UserTableListItem>({
    active: false,
    department: '',
    id: 0,
    name: '',
    username: '',
  }); // 操作的表格行
  const [identityModalVisible, handleIdentityModalVisible] = useState<boolean>(false); // 关联用户弹框

  const [queryParams, setQueryParams] = useState<{}>({}); // 表格搜索字段

  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();

  // 显示权限管理弹框
  const authorityManagement = (item: UserTableListItem) => {
    setDistributionObj(item);
    handleUpdateModalVisible(true);
  };

  const columns: ProColumns<IOrganizeTableItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '有效期(起）',
      dataIndex: 'validity',
      hideInSearch: true,
    },
    {
      title: '有效期(止）',
      dataIndex: 'invalid',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'active',
      valueEnum: {
        true: {
          text: '生效中',
          status: 'Success',
        },
        false: {
          text: '未生效',
          status: 'Error',
        },
      },
    },
    {
      title: '创建人',
      dataIndex: 'userId',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => (
        <>
          <a
            onClick={() => {
              authorityManagement(record);
            }}
          >
            权限管理
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleIdentityModalVisible(true);
            }}
          >
            关联用户
          </a>
          <Divider type="vertical" />
          <a>编辑</a>
        </>
      ),
    },
  ];

  const testDataSource = [
    {
      name: '财务指标查询',
      validity: '2020/08/22',
      invalid: '2020/08/23',
      active: false,
      userId: 'xiaojie',
    },
    {
      name: '财务指标查询',
      validity: '2020/08/22',
      invalid: '2020/08/23',
      active: false,
      userId: 'xiaojie',
    },
    {
      name: '财务指标查询',
      validity: '2020/08/22',
      invalid: '2020/08/23',
      active: false,
      userId: 'xiaojie',
    },
  ];

  // 获得表格滚动区域高度
  let tabelScroll = 300;
  const wrapperRef = useRef<any>();

  if (wrapperRef && wrapperRef.current) {
    tabelScroll = wrapperRef.current.scrollHeight - 280;
  }

  return (
    <div>
      <ProTable<IOrganizeTableItem>
        actionRef={actionRef}
        scroll={{y: tabelScroll}}
        rowKey="name"
        options={{
          fullScreen: true,
          reload: false,
          setting: true,
          density: true,
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<IOrganizeTableItem>;

          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        dataSource={testDataSource.filter((value) => {
          const keys = Object.keys(queryParams);
          if (keys.length === 0) {
            return true;
          } else {
            for (let i in keys) {
              const key = keys[i];
              if (value[key].toString().indexOf(queryParams[key]) === -1) {
                return false;
              }
            }
          }
          return true;
        })}
        onSubmit={(params) => {
          setQueryParams(params);
        }}
        columns={columns}
      />

      {/* 权限管理弹框 */}
      {updateModalVisible ? (
        <React.Suspense fallback={null}>
          <RightsManagement
            userId={distributionObj.id}
            parentType="Temporary"
            onCancel={() => {
              handleUpdateModalVisible(false);
            }}
            visible={updateModalVisible}
          />
        </React.Suspense>
      ) : null}

      {/* 新建弹框 */}
      <React.Suspense fallback={null}>
        <AddModel visible={createModalVisible} onCancel={() => handleModalVisible(false)} />
      </React.Suspense>

      {/* 关联用户弹框 */}
      {identityModalVisible ? (
        <React.Suspense fallback={null}>
          <RelationModel
            modalVisible={identityModalVisible}
            onCancel={() => {
              handleIdentityModalVisible(false);
            }}
          />
        </React.Suspense>
      ) : (
        ''
      )}
    </div>
  );
};
export default connect(({}: ConnectState) => ({}))(TemporaryAuthority);
